<template>
  <div class="score-list-container">
    <el-card>
      <template #header>
        <div class="search-header">
          <el-input
            v-model="searchQuery"
            placeholder="请输入搜索内容"
            clearable
            class="search-input"
            size="default"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" size="default" @click="handleSearch"
            >搜索</el-button
          >
          <el-button size="default" @click="handleReset">重置</el-button>
          <el-button type="success" size="default" @click="openAddScoreDialog"
            >添加成绩</el-button
          >
          <el-button
            type="danger"
            size="default"
            @click="deleteSelectedScores"
            :disabled="!selectedScores.length"
            >批量删除</el-button
          >
          <el-button
            type="info"
            size="default"
            @click="handleExport"
            >导出CSV</el-button
          >
        </div>
      </template>
      <el-table
        :data="filteredScores"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        ref="scoreTable"
      >
        <el-table-column type="selection" min-width="30" />
        <el-table-column
          type="index"
          label="序号"
          min-width="60"
          align="center"
        >
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="courseName"
          align="center"
          label="课程名"
          min-width="180"
        />
        <el-table-column
          prop="studentName"
          align="center"
          label="学生名"
          min-width="120"
        />
        <el-table-column
          prop="grade"
          align="center"
          label="成绩"
          min-width="80"
        >
          <template #default="scope">
            <el-tag :type="scope.row.grade >= 80 ? 'success' : (scope.row.grade >= 60 ? 'warning' : 'error')">
              {{ scope.row.grade }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="enterTime"
          label="录入时间"
          align="center"
          min-width="180"
        />
       
        <el-table-column label="操作" align="center" min-width="200">
          <template #default="scope">
            <el-button
              text
              type="primary"
              size="default"
              @click="openEditScoreDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              text
              type="danger"
              size="default"
              @click="delScore(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :pager-count="9"
          layout="prev, pager, next"
          :total="total"
          prev-text="上一页"
          next-text="下一页"
        />
      </div>
    </el-card>

    <!-- 添加/编辑成绩弹框 -->
    <el-dialog
      :title="dialogTitle"
      align-center
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        :model="currentScore"
        :rules="rules"
        ref="scoreForm"
        label-width="80px"
        class="dialog-form"
      >
        <el-form-item label="课程名" prop="courseId">
          <el-select
            v-model="currentScore.courseId"
            placeholder="请选择课程"
            class="dialog-input"
          >
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学生名" prop="studentId">
          <el-select
            v-model="currentScore.studentId"
            placeholder="请选择学生"
            class="dialog-input"
          >
            <el-option
              v-for="student in students"
              :key="student.id"
              :label="student.name"
              :value="student.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成绩" prop="grade">
          <el-input
            v-model="currentScore.grade"
            placeholder="请输入成绩"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="录入时间" prop="enterTime">
          <el-date-picker
            v-model="currentScore.enterTime"
            type="date"
            placeholder="请选择录入时间"
            class="dialog-input"
            
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveScore">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  getScoreList,
  addScore,
  updateScore,
  deleteScore,
  deleteScores,
  getAllCourse,
  getAllStudent,
} from "@/request/request";

const searchQuery = ref("");
const scores = ref([]);
const courses = ref([]);
const students = ref([]);

const selectedScores = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref("添加成绩");
const currentScore = ref({
  courseId: null,
  studentId: null,
  grade: null,
  enterTime: null,
});

const rules = {
  courseId: [{ required: true, message: "请选择课程", trigger: "blur" }],
  studentId: [{ required: true, message: "请选择学生", trigger: "blur" }],
  grade: [{ required: true, message: "请输入成绩", trigger: "blur" }],
};

// 添加分页相关的响应式数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const scoreForm = ref(null);

onMounted(() => {
  getScores();
  getCourses();
  getStudents();
});

// 获取所有课程
const getCourses = async () => {
  const res = await getAllCourse();
  if (res.code == 200) {
    courses.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 获取所有学生
const getStudents = async () => {
  const res = await getAllStudent();
  if (res.code == 200) {
    students.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 获取成绩列表
const getScores = async () => {
  try {
    const res = await getScoreList(currentPage.value, pageSize.value);
    scores.value = res.data.records;
    total.value = res.data.total; // 设置总数据量
  } catch (error) {
    console.error("获取成绩列表失败", error);
  }
};

const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置页码到第一页
};

const filteredScores = computed(() => {
  if (!searchQuery.value) {
    return scores.value; // 当搜索框为空时，直接返回原始数据
  }
  return scores.value.filter((score) => {
    return (
      (score.courseName &&
        score.courseName.toLowerCase().includes(searchQuery.value.toLowerCase())) ||
      (score.studentName &&
        score.studentName.toLowerCase().includes(searchQuery.value.toLowerCase())) ||
      (score.enterTime &&
        score.enterTime.toLowerCase().includes(searchQuery.value.toLowerCase()))
    );
  });
});

const handleReset = () => {
  searchQuery.value = "";
};

const openAddScoreDialog = () => {
  dialogTitle.value = "添加成绩";
  currentScore.value = {
    courseId: null,
    studentId: null,
    grade: null,
    enterTime: null,
  };
  dialogVisible.value = true;
  // 重置表单校验
  if (scoreForm.value) {
    scoreForm.value.resetFields();
  }
};

const openEditScoreDialog = (score) => {
  dialogTitle.value = "编辑成绩";
  currentScore.value = { ...score };
  dialogVisible.value = true;
  // 重置表单校验
  if (scoreForm.value) {
    scoreForm.value.resetFields();
  }
};

const handleSaveScore = () => {
  scoreForm.value.validate(async (valid) => {
    if (valid) {
      if (dialogTitle.value === "添加成绩") {
        appendScore();
      } else {
        editScore();
      }
    }
  });
};

const appendScore = async () => {
  // 添加成绩逻辑
  const res = await addScore(currentScore.value);
  if (res.code == 200) {
    ElMessage.success(res.msg);
    dialogVisible.value = false;
    getScores();
  } else {
    ElMessage.error(res.msg);
  }
};

const editScore = async () => {
  // 编辑成绩逻辑
  const res = await updateScore(currentScore.value.id, currentScore.value);
  if (res.code == 200) {
    ElMessage.success(res.msg);
    dialogVisible.value = false;
    getScores();
  } else {
    ElMessage.error(res.msg);
  }
};

const delScore = async (score) => {
  // 删除成绩逻辑
  ElMessageBox.confirm("确定要删除该成绩吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteScore(score.id);
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getScores();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const deleteSelectedScores = async () => {
  // 批量删除成绩逻辑
  const ids = selectedScores.value.map((score) => score.id);
  console.log(ids);
  ElMessageBox.confirm("确定要删除这些成绩吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteScores(ids);
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getScores();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSelectionChange = (val) => {
  selectedScores.value = val;
};

// 分页事件
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getScores();
};

// 导出功能
const handleExport = () => {
  exportToCSV();
};

const exportToCSV = () => {
  const array = [
    ["序号", "课程名", "学生名", "成绩", "录入时间"],
    ...scores.value.map((score, index) => [
      index + 1,
      score.courseName,
      score.studentName,
      score.grade,
      score.enterTime,
    ]),
  ];

  const csvContent = array.map((row) => row.join(",")).join("\n");
  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.setAttribute("href", url);
  link.setAttribute("download", "scores.csv");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style scoped>
.search-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.dialog-form {
  text-align: center;
}

.dialog-input {
  width: 100%;
  margin: 0 auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-button--info {
  background-color: #909399; /* 信息背景 */
  border-color: #909399; /* 信息边框 */
  color: white; /* 白色文字 */
}

.el-button--info:hover {
  background-color: #82848a; /* 鼠标悬停时的信息背景 */
  border-color: #82848a; /* 鼠标悬停时的信息边框 */
}
</style>
